#include "hudtext.h"
#include "osgButton.h"
#include "utility.h"
#include "datatypedefine.h"

namespace Gui2D
{
	HudText::HudText(osgWidget::WindowManager* manager,float positionZ)
	{
		_posZ = positionZ;
		_windowManager = manager;
	}

	HudText::~HudText()
	{}

	void HudText::addText(const QString& text,float xoff,float yoff,int textsize,const osg::Vec4& textcolor)
	{
		OsgTextStruct newtextstruct;
		newtextstruct._currentText = text;
		newtextstruct._xOff = xoff;
		newtextstruct._yOff = yoff;
		newtextstruct._textSize = textsize;
		newtextstruct._textColor = textcolor;
		newtextstruct._textNode = new osgText::Text;
		newtextstruct._textNode->setFont("fonts\\msyh.ttf");
		newtextstruct._textNode->setCharacterSize(newtextstruct._textSize);
		newtextstruct._parentNode = new osg::Geode;
		newtextstruct._parentNode->addDrawable(newtextstruct._textNode);
		newtextstruct._isShow = false;

		_textVector.push_back(newtextstruct);
	}

	void HudText::resizeWindowManager(float width,float height)
	{
		refresh();
	}

	void HudText::clear()
	{
		for(int i=0;i<_textVector.size();++i)
		{
			_windowManager->removeChild(_textVector.at(i)._parentNode);
			_textVector[i]._isShow  = false;
		}
		_textVector.clear();
	}

	void HudText::show()
	{
		for(int i=0;i<_textVector.size();++i)
		{
			if(_textVector[i]._isShow  == false)
			{
				_windowManager->addChild(_textVector.at(i)._parentNode);
				_textVector[i]._isShow = true;
			}
		}
		refresh();
	}

	void HudText::hide()
	{
		for(int i=0;i<_textVector.size();++i)
		{
			if(_textVector[i]._isShow  == true)
			{
				_windowManager->removeChild(_textVector.at(i)._parentNode);
				_textVector[i]._isShow = false;
			}
		}
	}

	void HudText::refresh()
	{
		setlocale(LC_ALL,".936");
		for(int i=0;i<_textVector.size();++i)
		{
			if(_textVector[i]._isShow)
			{
				std::string text = ChineseTexttoStdstring(_textVector.at(i)._currentText);
				char* charstr = (char*)text.c_str();
				int requiredsize = mbstowcs(NULL,charstr,0);
				wchar_t* wtext = new wchar_t[requiredsize+1];
				mbstowcs(wtext,charstr,requiredsize+1);
				_textVector[i]._textNode->setText(wtext);
				delete wtext;

				_textVector[i]._textNode->setPosition(osg::Vec3(_windowManager->getWidth()*_textVector[i]._xOff,
					_windowManager->getHeight()*_textVector[i]._yOff,_posZ));
			}
		}
	}
}